from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import permission_required
# Create your views here.

# 网站后台的首页
def index(request):
    
    return render(request,'admin/index.html')


# 文件上传的函数
def uploads(myfile):
    import time,random
    from lzy.settings import BASE_DIR

    filename = str(time.time())+str(random.randint(10000,99999))+'.'+myfile.name.split('.').pop()
    destination = open(BASE_DIR+"/static/pics/"+filename,"wb+")
    for chunk in myfile.chunks():      # 分块写入文件  
        destination.write(chunk)  
    destination.close()

    return "/static/pics/"+filename



# 登录
def mylogin(request):
    # 如果是get请求
    if request.method == 'GET':

        # 返回一个登录页面
        return render(request,'admin/login.html')

    elif request.method == 'POST':
                # 执行登录
        # 判断验证码是否正确
        # if request.POST['vcode'].lower() != request.session['verifycode'].lower():
            # return HttpResponse('<script>alert("验证码错误");location.href="/myadmin/login/"</script>')
        
        # 使用django提供的后台用户验证方法
        username = request.POST['username']
        password = request.POST['password']
        user = authenticate(request, username=username, password=password)
        if user:
            #登录
            login(request,user)
            return HttpResponse('<script>alert("登录成功");location.href="/myadmin/"</script>')
        
    return HttpResponse('<script>alert("用户名或密码错误");location.href="/myadmin/login/"</script>')


# 退出
def mylogout(request):
    # 退出登录
    logout(request)

    
    return HttpResponse('<script>alert("欢迎下次登录");location.href="/myadmin/login/"</script>')